package com.xuehu.filter;

import javax.servlet.*;
import java.io.IOException;

/**
 * 过滤器的作用
 * 拦截整个web项目的进出口
 */
public class CharacterEncodingFilter implements Filter {


    //初始化
    public void init(FilterConfig filterConfig) throws ServletException {
        filterConfig.getServletContext().setAttribute("init", "服务器启动时可以设置一些固有的属性，让所有servlet获取");
        System.out.println("CharacterEncodingFilter 初始化");
    }

    //Chain : 链
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        //全局编码配置
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        System.out.println("CharacterEncodingFilter 执行前....");

        chain.doFilter(request, response); //让我们的请求继续走，如果不写，程序到这个就停止了，出不去

        System.out.println("CharacterEncodingFilter 执行后....");
    }

    //销毁
    public void destroy() {
        System.out.println("CharacterEncodingFilter 销毁");
    }
}
